package me.tonywang.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.tonywang.sys.model.Pojo;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Api("CRUD功能测试")
@RestController
public class ReqController {

    /**
     * @param result
     * @Description 统一校验处理
     * @since V1.0
     */
    public void checkValidator(BindingResult result) {
        if (!result.hasErrors()) {
            return;
        }

        StringBuffer sb = new StringBuffer("");
        List<ObjectError> errors = result.getAllErrors();
        for (ObjectError e : errors) {
            sb.append(e.getDefaultMessage()).append(",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        throw new RuntimeException(sb.toString());
    }

    /**
     * @param req Content-Type: application/json;charset=utf-8
     * @return
     */

    @ApiOperation("缓存测试")
    @Cacheable(cacheNames = {"sampleCache"}, key = " ':'+ #req.name")
    @PostMapping("/reqbody")
    public Pojo reqbody(@RequestBody @Valid Pojo req, @RequestParam String name, BindingResult result) {
        checkValidator(result);
        System.out.println(name);
        return req;
    }

    @PostMapping("/delete")
    public List<String> delete(@RequestBody List<String> ids) {
        System.out.println(ids);
        return ids;
    }

    /**
     * @param req Content-Type: application/json;charset=utf-8
     * @return
     */
    @PostMapping("/reqbody2map")
    public Map reqbody(@RequestBody Map<String, Object> req, @RequestParam String key) {
        System.out.println(key);
        return req;
    }

    /**
     * @param req Content-Type: application/x-www-form-urlencoded;charset=utf-8
     * @return
     */
    @PostMapping("/reqform")
    public Pojo reqform(Pojo req) {
        return req;
    }

    /**
     * @param req Content-Type: application/x-www-form-urlencoded;charset=utf-8
     * @return
     */
    @PostMapping("/reqform2map")
    public Map reqform(@RequestParam Map<String, String> req) {
        return req;
    }

    @GetMapping("/getReq")
    public Pojo getReq(Pojo req) {
        return req;
    }

    @GetMapping("/getReq2")
    public String getReq2(Pojo req) {
        return "中文";
    }


    Scheduler scheduler;

    @Autowired(required = false)
    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }
}
